<template>
  <el-table
    :data="tableData"
    style="width: 100%; margin-bottom: 20px"
    row-key="id"
    border
    :default-expand-all="isExpandAll"
    v-if="refreshTable"
    max-height="660"
  >
    <el-table-column prop="skuCategoryName" label="分类名称" width="280" />
    <el-table-column prop="imageAtegory" label="分类图标" />
    <el-table-column fixed="right" label="操作" width="210" align="center">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="addCategory"
          ><el-icon><Plus /></el-icon>&nbsp;添加</el-button
        >
        <!-- 修改 -->
        <el-button type="primary" @click="editCategory(scope.row)" link
          ><el-icon><EditPen /></el-icon>修改</el-button
        >
        <!-- 删除 -->
        <el-button
          type="primary"
          @click="deleteCategory(scope.row, scope.row.id)"
          link
        >
          <el-icon><Delete /></el-icon>删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <categoryDialog ref="dialog"></categoryDialog>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import categoryDialog from "./CategoryDialog.vue";
import { useStore } from "vuex";
const store = useStore();

let isExpandAll = ref(false);
let refreshTable = ref(true);
let dialog = ref(); //存放弹窗组件ref
let props = defineProps(["tableData"]); //接收props

// 是否展开
const isExpand = () => {
  isExpandAll.value = !isExpandAll.value;
  refreshTable.value = !refreshTable.value;
  nextTick(() => {
    refreshTable.value = true;
  });
};

//添加
const addCategory = () => {
  dialog.value.openDialog("添加分类");
};

// 修改
const editCategory = (category: any) => {
  dialog.value.openDialog("修改分类", category);
};

// 删除
const deleteCategory = (category: any) => {
  ElMessageBox.confirm(
    `是否删除名称为 “${category.skuCategoryName}” 的分类？`,
    "Warning",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(async () => {
    try {
      let res = await store.dispatch("category/deleteCategory", category);
      console.log(res);
      ElMessage({
        message: "删除成功",
        type: "success",
        showClose: true
      });
    } catch (error: any) {
      ElMessage({
        message: error,
        type: "error",
        showClose: true
      });
    }
  });
};

defineExpose({
  isExpand
});
</script>

<style></style>
